package com.arron.ssm.service.impl;

import com.arron.ssm.dao.DeptMapper;
import com.arron.ssm.entity.Dept;
import com.arron.ssm.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Classname DeptServiceImpl
 * @Date 2020/9/24 16:42
 * @Created by 刘
 */
@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    DeptMapper deptMapper;

    @Override
    public List<Dept> getAllDeptByTree() {
        //拿到所有的部门信息
        List<Dept> depts = deptMapper.selectList();
        //构建树型结构
        List<Dept> depts1 = getChildDept(0L, depts);
        return depts1;
    }

    @Override
    public int addDept(Dept dept) {
        int insert = deptMapper.insert(dept);
        return insert;
    }

    @Transactional
    @Override
    public void removeById(Long id) {
        //拿到层级关系的部门集合
        List<Dept> childDept = getChildDept(id, deptMapper.selectList());
        //拿到要删除的子部门id集合
        ArrayList<Long> ids = new ArrayList<>();
        getChildrenId(childDept,ids);
        //然后进行批量删除
        if (ids.size()>0){
            //批量删除子部门
            deptMapper.deleteBatchByIds(ids);
        }
        //1.2删除自己
        deptMapper.deleteByPrimaryKey(id.intValue());
    }

    @Override
    public int update(Dept dept, Integer id) {
        return  deptMapper.updateByPrimaryKey(dept,id);
    }

    /**
     * 递归的拿到所有子级部门的id
     * @param childDept
     * @param ids
     */
    private void getChildrenId(List<Dept> childDept, ArrayList<Long> ids) {
        if (childDept!=null&&childDept.size()>0){
            for (Dept dept : childDept) {
                ids.add(dept.getId().longValue());
                getChildrenId(dept.getChilds(),ids);
            }
        }
        return;
    }

    private List<Dept> getChildDept(Long id,List<Dept> depts){
        if (depts!=null&&depts.size()>0){
            //过滤掉父节点
            List<Dept> collect = depts.stream().filter(item -> item.getPid() == id.intValue()).map(dept -> {
                //直接递归拿到父节点下所有孩子
                dept.setChilds(getChildDept(dept.getId().longValue(), depts));
                return dept;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

}
